import 'package:flutter/material.dart';
import 'package:isar/isar.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wallpaper/db/love.dart';

class LoveDatabase extends ChangeNotifier {
  static late Isar isar;
  // 初始化数据库
  static Future<void> initialize() async {
    final dir = await getApplicationDocumentsDirectory();
    isar = await Isar.open([LoveSchema], directory: dir.path);
  }

  // 收藏壁纸 初始为空
  final List<Love> loveImages = [];

  // 添加收藏
  Future<void> addLove(String smallPath, String largePath, String tags) async {
    List<Love> images = await getAllLove();
    // 通过smallPath检查是否已经收藏 有则删除
    int index = images.indexWhere((element) => element.smallPath == smallPath);
    if (index != -1) {
      removeLove(images[index]);
    } else {
      final newLove = Love()
        ..smallPath = smallPath
        ..largePath = largePath
        ..tags = tags;
      await isar.writeTxn(() async {
        await isar.loves.put(newLove);
        loveImages.add(newLove);
        notifyListeners();
      });
    }
  }

  // 删除收藏
  Future<void> removeLove(Love love) async {
    await isar.writeTxn(() async {
      await isar.loves.delete(love.id);
      loveImages.remove(love);
      notifyListeners();
    });
  }

  // 查看单个是否收藏
  Future<bool> isLove(String smallPath) async {
    List<Love> images = await getAllLove();
    return images.any((element) => element.smallPath == smallPath);
  }

  // 获取所有收藏
  Future<List<Love>> getAllLove() async {
    return await isar.loves.where().findAll();
  }

  // 删除所有收藏
  Future<void> removeAllLove() async {
    await isar.writeTxn(() async {
      await isar.loves.clear();
      loveImages.clear();
      notifyListeners();
    });
  }
}
